package com.example.project.intecetper;


import com.example.project.constant.Constants;
import com.example.project.exception.AuthException;
import com.example.project.utils.JwtUtils;
import com.example.project.utils.SecurityUtils;
import com.example.project.vo.model.AuthUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
 * 解析 token 看类上面是否带了 AuthLogin
 */
@Component
@Slf4j
@Order(1)
public class TokenInterceptor implements HandlerInterceptor {


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String token = StringUtils.isEmpty(request.getHeader(Constants.TOKEN_KEY)) ? null : request.getHeader(Constants.TOKEN_KEY);
        if (!StringUtils.isEmpty(token)) {
            AuthUser authUser = JwtUtils.parseToken(token);


            if (ObjectUtils.isEmpty(authUser)) {
                log.error("当前登入无效！");
                throw new AuthException(403,"当前登入无效！");
            }
            SecurityUtils.putUser(authUser);
        }
        //SecurityUtils.putToken(token);

        return HandlerInterceptor.super.preHandle(request, response, handler);
    }


    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //清楚用户信息 防止 内存泄漏
        SecurityUtils.removeResources();
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
